<template>
  <div class="score-filter">
    <el-form :inline="true" class="filter-form">
      <!-- 学期选择 -->
      <el-form-item label="学期">
        <el-select
          v-model="localFilters.termId"
          placeholder="选择学期"
          clearable
          style="width: 160px"
          @change="handleTermChange"
        >
          <el-option
            v-for="term in terms"
            :key="term.id"
            :label="term.name"
            :value="term.id"
          />
        </el-select>
      </el-form-item>

      <!-- 课程选择 -->
      <el-form-item label="课程">
        <el-select
          v-model="localFilters.courseId"
          placeholder="选择课程"
          clearable
          style="width: 200px"
          @change="handleCourseChange"
          :disabled="!filteredCourses.length"
        >
          <el-option
            v-for="course in filteredCourses"
            :key="course.id"
            :label="course.name"
            :value="course.id"
          />
        </el-select>
      </el-form-item>

      <!-- 教学任务选择 -->
      <el-form-item label="教学任务">
        <el-select
          v-model="localFilters.teachingMissionId"
          placeholder="选择教学任务"
          clearable
          style="width: 250px"
          @change="handleTeachingMissionChange"
          :disabled="!filteredTeachingMissions.length"
        >
          <el-option
            v-for="mission in filteredTeachingMissions"
            :key="mission.id"
            :label="getMissionLabel(mission)"
            :value="mission.id"
          />
        </el-select>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSearch" :disabled="!canSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'

// Props定义
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      termId: '',
      courseId: '',
      teachingMissionId: ''
    })
  },
  terms: {
    type: Array,
    default: () => []
  },
  courses: {
    type: Array,
    default: () => []
  },
  teachingMissions: {
    type: Array,
    default: () => []
  }
})

// Emits定义
const emit = defineEmits([
  'update:modelValue',
  'search',
  'reset',
  'term-change',
  'course-change'
])

// 本地筛选条件
const localFilters = ref({ ...props.modelValue })

// 深度比较函数，避免使用JSON.stringify的性能问题
const deepEqual = (obj1, obj2) => {
  if (obj1 === obj2) return true
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) {
    return false
  }
  
  const keys1 = Object.keys(obj1)
  const keys2 = Object.keys(obj2)
  
  if (keys1.length !== keys2.length) return false
  
  for (const key of keys1) {
    if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
      return false
    }
  }
  
  return true
}

// 监听props变化，同步到本地（仅在props变化时同步，避免循环）
watch(() => props.modelValue, (newValue) => {
  // 只有当newValue与localFilters不同时才同步，避免循环更新
  if (!deepEqual(newValue, localFilters.value)) {
    localFilters.value = { ...newValue }
  }
}, { deep: true })

// 监听本地变化，同步到父组件（仅在本地真正变化时才emit）
watch(localFilters, (newValue) => {
  // 只有当newValue与props.modelValue不同时才emit，避免循环更新
  if (!deepEqual(newValue, props.modelValue)) {
    emit('update:modelValue', { ...newValue })
  }
}, { deep: true })

// 计算属性：根据学期过滤课程
const filteredCourses = computed(() => {
  if (!localFilters.value.termId) {
    return props.courses
  }
  
  // 从教学任务中提取该学期下的课程
  const termMissions = props.teachingMissions.filter(mission => 
    String(mission.termId) === String(localFilters.value.termId)
  )
  
  const courseMap = new Map()
  termMissions.forEach(mission => {
    if (mission.courseId && mission.courseName) {
      courseMap.set(mission.courseId, {
        id: mission.courseId,
        name: mission.courseName,
        code: mission.courseCode || ''
      })
    }
  })
  
  return Array.from(courseMap.values())
})

// 计算属性：根据学期和课程过滤教学任务
const filteredTeachingMissions = computed(() => {
  let filtered = props.teachingMissions
  
  // 按学期过滤
  if (localFilters.value.termId) {
    filtered = filtered.filter(mission => 
      String(mission.termId) === String(localFilters.value.termId)
    )
  }
  
  // 按课程过滤
  if (localFilters.value.courseId) {
    filtered = filtered.filter(mission => 
      String(mission.courseId) === String(localFilters.value.courseId)
    )
  }
  
  return filtered
})

// 计算属性：是否可以搜索
const canSearch = computed(() => {
  return localFilters.value.teachingMissionId !== ''
})

// 获取教学任务标签
const getMissionLabel = (mission) => {
  if (!mission) return ''
  
  const parts = []
  if (mission.courseName) parts.push(mission.courseName)
  if (mission.classNames && mission.classNames.length > 0) {
    parts.push(mission.classNames.join(', '))
  }
  if (mission.teacherNames && mission.teacherNames.length > 0) {
    parts.push(`教师: ${mission.teacherNames.join(', ')}`)
  }
  
  return parts.join(' - ') || '未知教学任务'
}

// 事件处理：学期变化
const handleTermChange = (termId) => {
  // 清空课程和教学任务选择
  localFilters.value.courseId = ''
  localFilters.value.teachingMissionId = ''
  
  // 通知父组件
  emit('term-change', termId)
}

// 事件处理：课程变化
const handleCourseChange = (courseId) => {
  // 清空教学任务选择
  localFilters.value.teachingMissionId = ''
  
  // 通知父组件
  emit('course-change', courseId)
}

// 事件处理：教学任务变化
const handleTeachingMissionChange = (teachingMissionId) => {
  // 移除冗余的emit调用，因为watch已经会处理同步到父组件
  
  // 如果选择了教学任务，自动触发搜索
  if (teachingMissionId && canSearch.value) {
    emit('search', localFilters.value)
  }
}

// 事件处理：搜索
const handleSearch = () => {
  if (canSearch.value) {
    emit('search', localFilters.value)
  }
}

// 事件处理：重置
const handleReset = () => {
  localFilters.value = {
    termId: '',
    courseId: '',
    teachingMissionId: ''
  }
  emit('reset')
}
</script>

<style scoped>
.score-filter {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 16px;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0;
}

.filter-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.filter-form :deep(.el-select) {
  min-width: 160px;
}

.filter-form :deep(.el-button) {
  min-width: 80px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .filter-form :deep(.el-form-item) {
    width: 100%;
  }
  
  .filter-form :deep(.el-select) {
    width: 100%;
  }
}

/* 禁用状态样式 */
.filter-form :deep(.el-select.is-disabled .el-input__inner) {
  color: #c0c4cc;
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>